package kercar.manager;

import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;

import kercar.debug.Debugger;

public class MailManager {
	
	/************************************************************************* BLOCK
	 * ATTRIBUTES
	 *******************************************************************************/
	
	private final static String USERNAME = "keriositylsi@gmail.com";
	private final static String PASSWORD = "esir2lsi";

	/************************************************************************* BLOCK
	 * PUBLIC METHODS
	 *******************************************************************************/
	
	public void send(int numPhoto, String rec) {
		Properties props = new Properties();
		props.put("mail.smtp.auth", "true");
		props.put("mail.smtp.starttls.enable", "true");
		props.put("mail.smtp.host", "smtp.gmail.com");
		props.put("mail.smtp.port", "587");

		Session session = Session.getInstance(props,
				new javax.mail.Authenticator() {
					protected PasswordAuthentication getPasswordAuthentication() {
						return new PasswordAuthentication(USERNAME, PASSWORD);
					}
				});

		try {

			Message message = new MimeMessage(session);
			message.setFrom(new InternetAddress("from-email@gmail.com"));
			message.setRecipients(Message.RecipientType.TO,
					InternetAddress.parse(rec));
			message.setSubject("Testing Subject");

			// Create a multipar message
			Multipart multipart = new MimeMultipart();
			// Create the message part
			BodyPart messageBodyPart = new MimeBodyPart();

			// Fill the message
			messageBodyPart.setText("This is message body");
			// Set text message part
			multipart.addBodyPart(messageBodyPart);

			// Part two is attachment
			messageBodyPart = new MimeBodyPart();
			String filename = "/home/pi/photos/webcam" + numPhoto + ".jpg";
			DataSource source = new FileDataSource(filename);
			messageBodyPart.setDataHandler(new DataHandler(source));
			messageBodyPart.setFileName(filename);
			multipart.addBodyPart(messageBodyPart);

			// Send the complete message parts
			message.setContent(multipart);

			Transport.send(message);

			Debugger.logMsg("E-mail has been sent");
		} catch (MessagingException e) {
			Debugger.logException(e);
		}
	}
}
